package org.ymf.task.once;

import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.ymf.dao.UserEsDao;
import org.ymf.entity.User;
import org.ymf.entity.UserEs;
import org.ymf.service.UserService;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 => 全量同步到 Elasticsearch
 * </p>
 *
 * @author Malphite
 * @since 2023-08-03
 */
@Slf4j
// todo 取消注释开启任务
// @Component
public class FullSyncUserToEs implements CommandLineRunner {

    @Resource
    private UserService userService;

    @Resource
    private UserEsDao userEsDao;

    @Override
    public void run(String... args) {
        List<User> list = userService.list();
        if (list.isEmpty()) return;
        List<UserEs> esList = list.stream().map(User :: transform).collect(Collectors.toList());
        final int pageSize = 500;
        int total = esList.size();
        log.info("FullSyncUserToEs start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            userEsDao.saveAll(esList.subList(i, end));
        }
        log.info("FullSyncUserToEs end, total {}", total);
    }

}
